package com.myown.listenner;

import com.myown.constant.ConstantInfo;
import com.myown.model.User;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * 账户单线登录<tt>session</tt>监听器 <p>
 *
 * 用户权限拦截器 <p>
 *
 * @author lincky
 * @version v1.0.0
 */

public class AccountSessionListenner implements HttpSessionAttributeListener {

    /**
     * 账户登录表 <p>
     * 存放所有用户登录账号信息 <p>
     */
    private volatile static Map<String, HttpSession> accountSessionMap = new HashMap<>();

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (this.isAccountSession(event)) {
            HttpSession eventSession = event.getSession();
            // 设置session不活动时间为30分
            eventSession.setMaxInactiveInterval(1800);

            String logonname = ((User) event.getValue()).getLogonname();

            HttpSession mapSession = accountSessionMap.get(logonname);

            /*
                若账户登录表中已存在该用户信息，表明该账户已异地登录:
                1.在已登录session中移除用户信息
                2.在已登录session中添加用户异地登陆信息
                3.在账户登录表中替换用户登录账户信息
             */
            if (mapSession != null) {
                mapSession.removeAttribute(ConstantInfo.Account.HTTP_GLOBAL_ACCOUNT);
                mapSession.setAttribute(ConstantInfo.Account.THE_OTHER_LOGONED, 0);
                accountSessionMap.remove(logonname);
            }

            /*
                每次登录都保证异地登录信息为空
             */
            if (eventSession.getAttribute(ConstantInfo.Account.THE_OTHER_LOGONED) != null) {
                eventSession.removeAttribute(ConstantInfo.Account.THE_OTHER_LOGONED);
            }

            accountSessionMap.put(logonname, eventSession);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (this.isAccountSession(event)) {
            accountSessionMap.remove(((User) event.getValue()).getLogonname());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        // 设置session不活动时间为30分
        session.setMaxInactiveInterval(1800);

        String logonname = ((User) event.getValue()).getLogonname();

        HttpSession logonedSession = accountSessionMap.get(logonname);
    }

    /**
     * 判断session是否在处理与用户登记有关的信息
     *
     * @param event session事件
     * @return
     */
    private boolean isAccountSession(HttpSessionBindingEvent event) {
        return ConstantInfo.Account.HTTP_GLOBAL_ACCOUNT.
                equals(event.getName());
    }
}
